<template>
  <div class="category-list">
    <a-page-header
      title="分类管理"
      sub-title="管理系统中的分类，包括新增、编辑、删除等操作。"
    />
    <a-divider />
    <a-card class="search-card">
      <template #title>
        <span>搜索条件</span>
        <a-divider type="vertical" />
      </template>
      <a-form layout="inline">
        <a-form-item label="分类名称">
          <a-input v-model:value="searchForm.name" placeholder="请输入分类名称" allowClear />
        </a-form-item>
        <a-form-item>
          <a-space>
            <a-button type="primary" @click="handleSearch">
              <template #icon><search-outlined /></template>查询
            </a-button>
            <a-button @click="resetSearch">
              <template #icon><reload-outlined /></template>重置
            </a-button>
            <a-button type="primary" @click="showAddModal" v-permission="'content:category:add'">
              <template #icon><plus-outlined /></template>新增分类
            </a-button>
          </a-space>
        </a-form-item>
      </a-form>
    </a-card>
    <a-row :gutter="16">
      <a-col :span="24">
        <a-card>
          <a-table 
              bordered
              :columns="columns" 
              :data-source="categoryList" 
              :loading="tableLoading" 
              :pagination="{
                  current: pagination.current,
                  pageSize: pagination.pageSize,
                  total: pagination.total,
                  showSizeChanger: true,
                  showQuickJumper: true,
                  showTotal: (total) => `共 ${total} 条记录`
              }"
              @change="handleTableChange"
              rowKey="id">
              <template #bodyCell="{ column, record }">
                  <template v-if="column.key === 'action'">
                  <a-space>
                      <a-button type="primary" @click="showEditModal(record)" v-permission="'content:category:edit'">
                        <template #icon><edit-outlined /></template>编辑
                      </a-button>
                      <a-popconfirm
                      title="确定要删除这个分类吗？这将同时删除关联的作品！"
                      @confirm="handleDelete(record.id)"
                      ok-text="确定"
                      cancel-text="取消"
                      >
                      <a-button type="primary" danger v-permission="'content:category:delete'">
                        <template #icon><delete-outlined /></template>删除
                      </a-button>
                      </a-popconfirm>
                  </a-space>
                  </template>
                  <template v-else-if="column.key === 'status'">
                  <a-tag :color="record.status === 1 ? 'green' : 'red'">
                      {{ record.status === 1 ? '启用' : '禁用' }}
                  </a-tag>
                  </template>
                  <template v-else-if="column.key === 'icon'">
                    <img v-if="record.icon" :src="`/api${record.icon}`" alt="图标" style="width: 32px; height: 32px; object-fit: cover; border-radius: 4px;" />
                    <span v-else>-</span>
                  </template>
              </template>
          </a-table>
        </a-card>
      </a-col>
    </a-row>

    <!-- 新增/编辑分类弹窗 -->
    <a-modal
      :title="modalTitle"
      :visible="modalVisible"
      @ok="handleModalOk"
      @cancel="handleModalCancel"
      :confirmLoading="modalLoading"
    >
      <a-form
        ref="formRef"
        :model="formState"
        :rules="rules"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 16 }"
      >
        <a-form-item label="分类名称" name="name">
          <a-input v-model:value="formState.name" placeholder="请输入分类名称" />
        </a-form-item>
        <a-form-item label="分类图标" name="icon">
          <a-upload
            v-model:file-list="fileList"
            name="file"
            list-type="picture-card"
            class="avatar-uploader"
            :show-upload-list="false"
            action="/api/upload"
            :before-upload="beforeUpload"
            @change="handleChange"
          >
            <img v-if="imageUrl" :src="imageUrl.startsWith('data:') ? imageUrl : `/api${imageUrl}`" alt="icon" style="width: 100%; height: 100%; border-radius: 8px; object-fit: cover" />
            <div v-else>
              <loading-outlined v-if="imageLoading"></loading-outlined>
              <plus-outlined v-else></plus-outlined>
              <div class="ant-upload-text">上传</div>
            </div>
          </a-upload>
        </a-form-item>
        <a-form-item label="分类描述" name="description">
          <a-textarea v-model:value="formState.description" placeholder="请输入分类描述" :rows="4" />
        </a-form-item>
        <a-form-item label="排序" name="sort">
          <a-input-number v-model:value="formState.sort" :min="0" style="width: 100%" />
        </a-form-item>
        <a-form-item label="状态" name="status">
          <a-select v-model:value="formState.status">
            <a-select-option :value="1">启用</a-select-option>
            <a-select-option :value="0">禁用</a-select-option>
          </a-select>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script>
import { defineComponent, ref, reactive, onMounted } from 'vue';
import { message, PageHeader } from 'ant-design-vue';
import { PlusOutlined, EditOutlined, DeleteOutlined, LoadingOutlined, SearchOutlined, ReloadOutlined } from '@ant-design/icons-vue';
import axios from 'axios';

export default defineComponent({
  name: 'CategoryList',
  components: {
    SearchOutlined,
    ReloadOutlined,
    PlusOutlined,
    EditOutlined,
    DeleteOutlined,
    LoadingOutlined,
    APageHeader: PageHeader,
  },
  setup() {
    const tableLoading = ref(false);
    const categoryList = ref([]);
    const imageUrl = ref('');
    const imageLoading = ref(false);
    const fileList = ref([]);
    const searchForm = reactive({
      name: ''
    });
    const pagination = reactive({
      current: 1,
      pageSize: 10,
      total: 0,
    });
    
    const getBase64 = (img, callback) => {
      const reader = new FileReader();
      reader.addEventListener('load', () => callback(reader.result));
      reader.readAsDataURL(img);
    };

    const beforeUpload = (file) => {
      const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
      if (!isJpgOrPng) {
        message.error('只能上传 JPG/PNG 格式的图片！');
      }
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        message.error('图片大小不能超过 2MB！');
      }
      return isJpgOrPng && isLt2M;
    };

    const handleChange = (info) => {
      if (info.file.status === 'uploading') {
        imageLoading.value = true;
        return;
      }
      if (info.file.status === 'done') {
        // 获取服务器返回的图片URL
        if (info.file.response.code === 200) {
          formState.icon = info.file.response.data;
          getBase64(info.file.originFileObj, (base64Url) => {
            imageUrl.value = base64Url;
            imageLoading.value = false;
          });
        } else {
          message.error('上传失败');
          imageLoading.value = false;
        }
      }
      if (info.file.status === 'error') {
        imageLoading.value = false;
        message.error('上传失败');
      }
    };

    const columns = [
      {
        title: '序号',
        key: 'index',
        width: 80,
        customRender: ({ index }) => index + 1
      },
      {
        title: '分类名称',
        dataIndex: 'name',
        key: 'name',
        customRender: ({ text }) => text || '-'
      },
      {
        title: '图标',
        dataIndex: 'icon',
        key: 'icon',
      },
      {
        title: '描述',
        dataIndex: 'description',
        key: 'description',
        customRender: ({ text }) => text || '-',
        ellipsis: true,
      },
      {
        title: '排序',
        dataIndex: 'sort',
        key: 'sort',
        customRender: ({ text }) => text || 0
      },
      {
        title: '状态',
        dataIndex: 'status',
        key: 'status',
      },
      {
        title: '创建时间',
        dataIndex: 'createTime',
        key: 'createTime',
        customRender: ({ text }) => text || '-'
      },
      {
        title: '操作',
        key: 'action',
        width: 200,
      }
    ];

    // 获取分类列表
    const fetchCategoryList = (page = pagination.current, pageSize = pagination.pageSize) => {
      tableLoading.value = true;
      
      const params = {
        current: page,
        size: pageSize,
        name: searchForm.name,
      };
      
      console.log('params', params); // 输出参数，用于调试
      axios.get('/api/category/page', { params })
        .then(response => {
          if (response.data.code === 200) {
            categoryList.value = response.data.data.records;
            pagination.total = response.data.data.total;
            pagination.current = page;
            pagination.pageSize = pageSize;
          } else {
            message.error(response.data.message || '获取分类列表失败');
          }
        })
        .catch(error => {
          console.error('获取分类列表失败:', error);
          message.error('获取分类列表失败');
        })
        .finally(() => {
          tableLoading.value = false;
        });
    };

    // 表格变化事件
    const handleTableChange = (pag) => {
      fetchCategoryList(pag.current, pag.pageSize);
    };

    // 搜索按钮点击事件
    const handleSearch = () => {
      // 搜索时重置到第一页
      fetchCategoryList(1, pagination.pageSize);
    };
    
    // 重置搜索条件
    const resetSearch = () => {
      searchForm.name = '';
      fetchCategoryList(1, pagination.pageSize);
    };

    // 新增/编辑弹窗相关
    const modalVisible = ref(false);
    const modalTitle = ref('新增分类');
    const modalLoading = ref(false);
    const isEdit = ref(false);
    const formRef = ref(null);
    const formState = reactive({
      id: null,
      name: '',
      icon: '',
      description: '',
      sort: 0,
      status: 1,
    });

    const rules = {
      name: [
        { required: true, message: '请输入分类名称', trigger: 'blur' },
        { max: 50, message: '分类名称不能超过50个字符', trigger: 'blur' }
      ],
      description: [
        { max: 200, message: '分类描述不能超过200个字符', trigger: 'blur' }
      ],
      sort: [
        { required: true, message: '请输入排序值', trigger: 'blur' }
      ],
      status: [
        { required: true, message: '请选择状态', trigger: 'change' }
      ],
    };

    // 显示新增弹窗
    const showAddModal = () => {
      modalTitle.value = '新增分类';
      isEdit.value = false;
      formState.id = null;
      formState.name = '';
      formState.icon = '';
      formState.description = '';
      formState.sort = 0;
      formState.status = 1;
      imageUrl.value = '';
      modalVisible.value = true;
    };

    // 显示编辑弹窗
    const showEditModal = (record) => {
      modalTitle.value = '编辑分类';
      isEdit.value = true;
      formState.id = record.id;
      formState.name = record.name;
      formState.icon = record.icon;
      formState.description = record.description;
      formState.sort = record.sort;
      formState.status = record.status;
      imageUrl.value = record.icon;
      modalVisible.value = true;
    };

    // 弹窗确认
    const handleModalOk = () => {
      formRef.value.validate().then(() => {
        modalLoading.value = true;
        const url = isEdit.value ? `/api/category/${formState.id}` : '/api/category';
        const method = isEdit.value ? 'put' : 'post';
        
        axios[method](url, formState)
          .then(response => {
            if (response.data.code === 200) {
              message.success(isEdit.value ? '编辑成功' : '新增成功');
              modalVisible.value = false;
              fetchCategoryList();
            } else {
              message.error(response.data.message || (isEdit.value ? '编辑失败' : '新增失败'));
            }
          })
          .catch(error => {
            console.error(isEdit.value ? '编辑失败:' : '新增失败:', error);
            message.error(isEdit.value ? '编辑失败' : '新增失败');
          })
          .finally(() => {
            modalLoading.value = false;
          });
      }).catch(error => {
        console.log('验证失败:', error);
      });
    };

    // 弹窗取消
    const handleModalCancel = () => {
      modalVisible.value = false;
    };

    // 删除分类
    const handleDelete = (id) => {
      axios.delete(`/api/category/${id}`)
        .then(response => {
          if (response.data.code === 200) {
            message.success('删除成功');
            fetchCategoryList();
          } else {
            message.error(response.data.message || '删除失败');
          }
        })
        .catch(error => {
          console.error('删除失败:', error);
          message.error('删除失败');
        });
    };

    onMounted(() => {
      fetchCategoryList();
    });

    return {
      tableLoading,
      categoryList,
      pagination,
      columns,
      fetchCategoryList,
      handleTableChange,
      handleSearch,
      resetSearch,
      modalVisible,
      modalTitle,
      modalLoading,
      formRef,
      formState,
      rules,
      showAddModal,
      showEditModal,
      handleModalOk,
      handleModalCancel,
      handleDelete,
      imageUrl,
      imageLoading,
      fileList,
      beforeUpload,
      handleChange,
      searchForm,
    };
  }
});
</script>

<style scoped>
.category-list {
    background-color: transparent;
}
</style>